package com.zqweb.gulimall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Configuration
public class GulimallFeignRequestHoldConfig {
    @Bean
    /*
    由于Feign远程调用构造新请求时，不会带上老请求自身拥有的任何header信息，导致后续业务逻辑无法使用header的信息，从而
    产生一些异常bug，所以需要给构造新请求时使用到的RequestInterceptor中重新设置上老请求的header信息
      */
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if(requestAttributes != null){
                    HttpServletRequest request = requestAttributes.getRequest();
                    // 其中Session相关的信息（JSessionId）就存放在Cookie中
                    String cookie = request.getHeader("Cookie");
                    requestTemplate.header("Cookie",cookie);

                }
            }
        };
    }


}
